package com.yc.c118s3plyspringboot.web;

import com.google.gson.Gson;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
// 配置连接地址
@ServerEndpoint("/mysocket/{id}")
public class MyWebSocket {
    // 1. SpringBoot 的WebSocket管理会以原型模式创建 MyWebSocket 对象，
    // 必须使用静态的map集合管理会话
    // 2. Hashtable 线程安全  HashMap 线程不安全
    // ArrayList 线程不安全  与  Vector 线程安全
    // 存放websocket会话对象的集合
    static Map<String, Session> sessionMap = new Hashtable<>();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) throws IOException {
        sessionMap.put(id, session);
        // 保存用户的id, 可以保存用户的相关信息
        session.getUserProperties().put("id", id);
        // 在连接时，发送在线人数
        Message message = new Message();
        // stream
        List<String> list = sessionMap.keySet().stream().collect(Collectors.toList());
        message.setOnlines(list);
        RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
        Gson gson = new Gson();
        basicRemote.sendText(gson.toJson(message));
    }

    // 关闭连接
    @OnClose
    public void  onClose(Session session){
        // 从会话集合中移除会话
        String id = (String) session.getUserProperties().get("id");
        sessionMap.remove(id);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException{
        Message m = new Message();
        Map<String, Object> userProperties = session.getUserProperties();
        m.setId((String) userProperties.get("id"));
        m.setText(message);
        List<String> list = sessionMap.keySet().stream().collect(Collectors.toList());
        m.setOnlines(list);
        Gson gson = new Gson();
        String json = gson.toJson(m);
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()){
            String id = entry.getKey();
            Session sess = entry.getValue();
            RemoteEndpoint.Basic basicRemote = sess.getBasicRemote();
            basicRemote.sendText(json);
        }
    }

    @Scheduled(cron = "0 0 18 * * ?")
    public void sendGG() throws IOException {
        Message m = new Message();
        m.setId("系统");
        m.setText("17:30下课！！");
        String json = new Gson().toJson(m);
        for (Map.Entry<String, Session> entry : sessionMap.entrySet()){
            String id = entry.getKey();
            Session sess = entry.getValue();
            RemoteEndpoint.Basic basicRemote = sess.getBasicRemote();
            basicRemote.sendText(json);
        }
    }
}
